import 'package:sqflite/sqflite.dart';
import 'data_base_helper.dart';


class UserRepository {
  final DatabaseHelper _dbHelper = DatabaseHelper();

  // 验证用户名和密码是否正确
  Future<bool> validateUser(String username, String password) async {
    // 获取数据库实例
    Database db = await _dbHelper.database;

    // 查询数据库中是否存在匹配的用户名和密码
    List<Map<String, dynamic>> result = await db.query(
      'users',
      where: 'username = ? AND password = ?',
      whereArgs: [username, password],
    );

    // 如果查询结果不为空，说明用户名和密码正确
    return result.isNotEmpty;
  }

  // 验证用户名是否存在
  Future<bool> validateUserIsExist(String username) async {
    // 获取数据库实例
    // 检查用户名是否已存在
    bool exists = await _dbHelper.isUsernameExists(username);
    return exists;
  }

  // 其他用户相关方法...
  Future<bool> registerUser({
    required String username,
    required String password,
    required String securityQuestion,
    required String securityAnswer,
  }) async {

    // 检查用户名是否已存在
    bool exists = await _dbHelper.isUsernameExists(username);
    if (exists) {
      return false;
    }

    // 创建用户对象
    User user = User(
      username: username,
      password: password,
      securityQuestion: securityQuestion,
      securityAnswer: securityAnswer,
    );
    int id = await _dbHelper.insertUser(user);

    return id > 0; // 注册成功
  }

  // 获取用户安全问题
  Future<User?> getUserFromUsername(String username) async {
    User? user = await _dbHelper.queryUserByUsername(username);
    return user;
  }
}
